package com.harmony.pilot.knowledge.repository;

import com.harmony.pilot.knowledge.entity.CodeSnippet;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 代码片段Repository
 */
@Repository
public interface CodeSnippetRepository extends JpaRepository<CodeSnippet, Long> {
    
    /**
     * 根据文件路径查找
     */
    List<CodeSnippet> findByFilePath(String filePath);
    
    /**
     * 根据模块名查找
     */
    List<CodeSnippet> findByModuleName(String moduleName);
    
    /**
     * 根据片段类型查找
     */
    List<CodeSnippet> findBySnippetType(String snippetType);
    
    /**
     * 根据关键词查找
     */
    @Query("SELECT s FROM CodeSnippet s WHERE s.keywords LIKE %:keyword%")
    List<CodeSnippet> findByKeywordsContaining(@Param("keyword") String keyword);
    
    /**
     * 根据摘要查找
     */
    @Query("SELECT s FROM CodeSnippet s WHERE s.summary LIKE :pattern")
    List<CodeSnippet> findBySummaryContaining(@Param("pattern") String pattern);
    
    /**
     * 根据内容查找
     */
    @Query("SELECT s FROM CodeSnippet s WHERE s.content LIKE %:text%")
    List<CodeSnippet> findByContentContaining(@Param("text") String text);
    
    /**
     * 查找测试文件中包含指定文本的片段
     */
    @Query("SELECT s FROM CodeSnippet s WHERE s.isTest = true AND s.content LIKE %:text%")
    List<CodeSnippet> findByIsTestTrueAndContentContaining(@Param("text") String text);
    
    /**
     * 根据类型和关键词查找
     */
    @Query("SELECT s FROM CodeSnippet s WHERE s.snippetType = :type AND s.keywords LIKE %:keyword%")
    List<CodeSnippet> findBySnippetTypeAndKeywordsContaining(
        @Param("type") String type, 
        @Param("keyword") String keyword
    );
    
    /**
     * 查找Fuzzer文件
     */
    List<CodeSnippet> findByIsFuzzerTrue();
    
    /**
     * 查找Mock文件
     */
    List<CodeSnippet> findByIsMockTrue();
    
    /**
     * 根据文件MD5查找
     */
    List<CodeSnippet> findByFileMd5(String fileMd5);
    
    /**
     * 统计各类型片段数量
     */
    @Query("SELECT s.snippetType, COUNT(s) FROM CodeSnippet s GROUP BY s.snippetType")
    List<Object[]> countBySnippetType();
    
    /**
     * 统计各模块片段数量
     */
    @Query("SELECT s.moduleName, COUNT(s) FROM CodeSnippet s GROUP BY s.moduleName")
    List<Object[]> countByModuleName();
}

